package com.chenjun.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class FileUtil {

	// 上传excel文档的配置xml路径
	private static String excelConfigPath = null;

	/**
	 * 写入文本文件
	 * 
	 * @param filePath
	 * @param fileContent
	 * @param ecoding
	 */
	public static void writeTxtFile(String filePath, String fileContent, String ecoding) {
		try {
			File file = new File(filePath);
			if (!file.exists()) {
				file.createNewFile();
			}
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), ecoding);
			BufferedWriter writer = new BufferedWriter(write);
			writer.write("");
			writer.flush();
			writer.write(fileContent);
			writer.close();
		} catch (IOException e) {
			// Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 读取文本文件
	 * 
	 * @param filePath
	 * @param ecoding
	 * @return
	 */
	public static String readTxtFile(String filePath, String ecoding) {
		try {
			String encoding = "UTF-8";
			StringBuffer strBuffer = new StringBuffer();
			File file = new File(filePath);
			if (file.exists() && file.isFile()) {
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					strBuffer.append(lineTxt);
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
			return strBuffer.toString();
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 判断文件是否存在，判断文件大小是否为0.
	 * 
	 * @param path
	 * @return 文件不存在，返回false，文件存在，大小为0时返回false;
	 */
	public static boolean fileValidate(String path) {
		File file = new File(path);
		try {
			if (!file.exists()) {
				return false;
			} else {
				if (new FileInputStream(file).available() == 0) {
					return false;
				}
				return true;
			}
		} catch (Exception e) {
			// handle exception
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 得到上传excel表格路径
	 * 
	 * @param request
	 * @return
	 */
	public static String getExcelConfigFilePath(HttpServletRequest request) {

		if (request == null) {
			return excelConfigPath;
		}

		if (excelConfigPath == null) {
			Properties p = new Properties();
			try {
				@SuppressWarnings("deprecation")
				String path = request.getRealPath("/");
				String configpath = path + File.separator + "WEB-INF" + File.separator + "classes" + File.separator
						+ "config.properties";
				InputStream in = new FileInputStream(configpath);
				p.load(in);
				in.close();
				excelConfigPath = path + p.getProperty("excelconfigfilepath");

			} catch (Exception e) {

			}
		}

		return excelConfigPath;

	}

	/**
	 * Spring multipartFile文件上传
	 * 
	 * @return 文件上传后路径
	 */
	public static String multipartFileUpload(String savePath, HttpServletRequest request) {
		File saveDir = new File(savePath);
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		String pathResult = "";
		try {
			Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, MultipartFile> entry = it.next();
				MultipartFile mFile = entry.getValue();
				String fileName = mFile.getOriginalFilename();
				pathResult = savePath + File.separator + fileName;
				FileCopyUtils.copy(mFile.getBytes(), new File(pathResult));
			}
		} catch (Exception e) {
			// Auto-generated catch block
			e.printStackTrace();
		}
		return pathResult;
	}

	public static String newDirOnServer(String _dirName, String _currentPath, String _serverPath) {
		String respStr = "";
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(_serverPath);
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("DirName", _dirName);
		paramMap.put("CurrentPath", _currentPath);
		method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
		Iterator<String> iterator = paramMap.keySet().iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			method.setParameter(key, paramMap.get(key).toString());
		}
		int statusCode;
		try {
			statusCode = client.executeMethod(method);
			if (statusCode != HttpStatus.SC_OK) {
				System.out.println("Method failed: " + method.getStatusLine());
			}
			respStr = new String(method.getResponseBodyAsString().getBytes("GBK"), "GBK");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 释放连接
			method.releaseConnection();
		}
		return respStr;
	}

	/**
	 * 将文件拷贝到服务器
	 * 
	 * @param _filePath
	 *            文件地址
	 * @param _serverPath
	 *            服务器目录地址
	 * @return
	 */
	public static String copyFileToServer(String _savePath, String localPath, String _filePath, String _serverPath) {
		File targetFile = new File(_filePath);// 指定上传文件
		PostMethod filePost = new PostMethod(_serverPath);
		String response = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String date = sdf.format(new Date());
		_savePath = _savePath + "/" + date + "/";
		System.out.println(_savePath);
		try {
			System.out.println("targetFile.getName():" + targetFile.getName());
			StringPart strParts = new StringPart("savePath", _savePath);
			Part[] parts = { new CustomFilePart(targetFile.getName(), targetFile), strParts };
			filePost.setParameter("savePath", _savePath);
			filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
			int status = client.executeMethod(filePost);
			if (status == HttpStatus.SC_OK) {
				System.out.println("上传成功");
				response = filePost.getResponseBodyAsString();
				removeLocalhostImg(localPath, targetFile.getName());
				// 上传成功
			} else {
				System.out.println("上传失败");
				// 上传失败
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			filePost.releaseConnection();
		}
		return response;
	}

	/**
	 * 将文件拷贝到服务器(不删除本地文件)
	 * 
	 * @param _filePath
	 *            文件地址
	 * @param _serverPath
	 *            服务器目录地址
	 * @return
	 */
	/*
	 * public static String copyFilesToServer(String _savePath, String
	 * localPath, String _filePath, String _serverPath) { File targetFile = new
	 * File(_filePath);// 指定上传文件 PostMethod filePost = new
	 * PostMethod(_serverPath); String response = ""; try {
	 * System.out.println("targetFile.getName():" + targetFile.getName());
	 * StringPart strParts = new StringPart("savePath", _savePath); Part[] parts
	 * = { new CustomFilePart(targetFile.getName(), targetFile), strParts };
	 * filePost.setParameter("savePath", _savePath);
	 * filePost.setRequestEntity(new MultipartRequestEntity(parts,
	 * filePost.getParams())); HttpClient client = new HttpClient();
	 * client.getHttpConnectionManager().getParams()
	 * .setConnectionTimeout(5000); int status = client.executeMethod(filePost);
	 * if (status == HttpStatus.SC_OK) { System.out.println("上传成功"); response =
	 * filePost.getResponseBodyAsString(); // 上传成功 } else {
	 * System.out.println("上传失败"); // 上传失败 } } catch (Exception ex) {
	 * ex.printStackTrace(); } finally { filePost.releaseConnection(); } return
	 * response; }
	 */

	/**
	 * 删除本地服务器中预上传的图片
	 * 
	 * @param fileStrObj
	 */
	public static void removeLocalhostImg(String _localPath, String _fileName) {
		if (StringUtils.isBlank(_localPath)) {
			DeleteFolder(_fileName);
		} else {
			DeleteFolder(_localPath);
		}

	}

	/**
	 * 根据路径删除指定的目录或文件，无论存在与否
	 * 
	 * @param sPath
	 *            要删除的目录或文件
	 * @return 删除成功返回 true，否则返回 false。
	 */
	public static boolean DeleteFolder(String sPath) {
		File file = new File(sPath);
		// 判断目录或文件是否存在
		if (!file.exists()) { // 不存在返回 false
			return false;
		} else {
			// 判断是否为文件
			if (file.isFile()) { // 为文件时调用删除文件方法
				return deleteFile(sPath);
			} else { // 为目录时调用删除目录方法
				return deleteDirectory(sPath);
			}
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param sPath
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	public static boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			flag = file.delete();
		}
		return flag;
	}

	/**
	 * 把获取到的数据对应excel字段列位置对应添加(XLS格式)
	 * 
	 * @author huanghao
	 * @param List<String>
	 *            columns excel头文件字段,,List<List<String>> values
	 *            字段对应的每一行列的数据,String fileName 下载后的文件名
	 * @param ecoding
	 * @return
	 */
	public static File generatorXLSExecl(List<String> columns, List<List<String>> values, String fileName) {
		File file = null;
		int sheetNum = 1;
		HSSFWorkbook workBook = new HSSFWorkbook();
		HSSFCellStyle headstyle = workBook.createCellStyle();
		headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		for (int i = 0; i < sheetNum; i++) {
			HSSFSheet sheet = workBook.createSheet("sheet" + sheetNum);
			HSSFRow headRow = sheet.createRow(0);
			for (int j = 0; j < values.size(); j++) {
				HSSFRow row = sheet.createRow((short) (j + 1));
				List<String> rowData = values.get(j);
				// sheet.setColumnWidth(j,10000);
				for (int k = 0; k < columns.size(); k++) {
					HSSFCell headCell = headRow.createCell(k);
					headCell.setCellValue(columns.get(k));
					headCell.setCellStyle(headstyle);
					HSSFCell cell = row.createCell(k);
					cell.setCellValue(rowData.get(k));
					cell.setCellStyle(headstyle);
				}

			}
		}

		OutputStream os = null;
		String realPath = FileUtil.class.getResource("/").getPath();
		try {
			while (true) {
				File f = new File(realPath);
				if (null == f.getParent()) {
					break;
				}
				realPath = f.getParent();
			}

			File f = new File(realPath + "health_upload/" + fileName + "/");
			if (!f.exists()) {
				f.mkdirs();
			}
			String path = f.toString();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			String temp = dateFormat.format(new Date());
			file = new File(path + "/" + temp + "-" + fileName + ".xls");
			os = new FileOutputStream(file);
			workBook.write(os);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	/**
	 * 把获取到的数据对应excel字段列位置对应添加(xlsx格式)
	 * 
	 * @author huanghao
	 * @param List<String>
	 *            columns excel头文件字段,,List<List<String>> values
	 *            字段对应的每一行列的数据,String fileName 下载后的文件名
	 * @param ecoding
	 * @return
	 */
	public static File generatorExecl(List<String> columns, List<List<String>> values, String fileName) {
		File file = null;
		int sheetNum = 1;
		SXSSFWorkbook workBook = new SXSSFWorkbook(100);
		CellStyle headstyle = workBook.createCellStyle();
		headstyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
		headstyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中

		if (values.size() > 0) {// 有数据直接遍历根据excel标题对应各行数据
			for (int i = 0; i < sheetNum; i++) {
				org.apache.poi.ss.usermodel.Sheet sheet = workBook.createSheet("sheet" + sheetNum);
				org.apache.poi.ss.usermodel.Row headRow = sheet.createRow(0);
				for (int j = 0; j < values.size(); j++) {
					org.apache.poi.ss.usermodel.Row row = sheet.createRow((short) (j + 1));
					List<String> rowData = values.get(j);
					// sheet.setColumnWidth(j,10000);
					for (int k = 0; k < columns.size(); k++) {
						org.apache.poi.ss.usermodel.Cell headCell = headRow.createCell(k);
						headCell.setCellValue(columns.get(k));
						headCell.setCellStyle(headstyle);
						org.apache.poi.ss.usermodel.Cell cell = row.createCell(k);
						cell.setCellValue(rowData.get(k));
						cell.setCellStyle(headstyle);
					}

				}
			}
		} else {// 无数据直接遍历只根据excel标题
			for (int i = 0; i < sheetNum; i++) {
				org.apache.poi.ss.usermodel.Sheet sheet = workBook.createSheet("sheet" + sheetNum);
				org.apache.poi.ss.usermodel.Row headRow = sheet.createRow(0);

				for (int k = 0; k < columns.size(); k++) {
					org.apache.poi.ss.usermodel.Cell headCell = headRow.createCell(k);
					headCell.setCellValue(columns.get(k));
					headCell.setCellStyle(headstyle);

				}

			}
		}

		OutputStream os = null;
		String realPath = FileUtil.class.getResource("/").getPath();
		try {
			while (true) {
				File f = new File(realPath);
				if (null == f.getParent()) {
					break;
				}
				realPath = f.getParent();
			}

			File f = new File(realPath + "health_upload/" + fileName + "/");
			if (!f.exists()) {
				f.mkdirs();
			}
			String path = f.toString();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			String temp = dateFormat.format(new Date());
			file = new File(path + "/" + temp + "-" + fileName + ".xlsx");
			os = new FileOutputStream(file);
			workBook.write(os);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	/**
	 * 删除目录（文件夹）以及目录下的文件
	 * 
	 * @param sPath
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	public static boolean deleteDirectory(String sPath) {
		boolean flag = false;
		// 如果sPath不以文件分隔符结尾，自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			} // 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag)
			return false;
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据券号生成二维码并上传服务器
	 * 
	 * @return
	 * @param _filePath
	 *            文件地址
	 * @param _serverPath
	 *            服务器目录地址 ticketNumber 券号
	 * 
	 */
	/*
	 * public static String encoderQRCode(String serverPath, Profile file) { //
	 * Profile file = new Profile(); // file.setPath(path); //
	 * file.setFormat("png"); // file.setContent(ticketNumber); //
	 * file.setCharacterSet("gb2312"); // file.setMargin(0); //
	 * file.setWidth(width); // file.setHeight(height); //
	 * file.setLogoFlag(false); // file.setLogoPath(logoPath); //
	 * file.setErrorCorrectionLevel(ErrorCorrectionLevel.L); String path =
	 * System.getProperty("user.dir") + "/file";// 本地路径 if (file == null) {
	 * return null; } if (StringUtils.isEmpty(file.getPath())) {
	 * file.setPath(path); } if (StringUtils.isEmpty(file.getFormat())) {
	 * file.setFormat("png"); } if (StringUtils.isEmpty(file.getLogoPath())) {
	 * file.setLogoFlag(false); } if
	 * (StringUtils.isEmpty(file.getCharacterSet())) {
	 * file.setCharacterSet("gb2312"); } if (file.getHeight() == 0) {
	 * file.setHeight(140); } if (file.getWidth() == 0) { file.setWidth(140); }
	 * if (file.getErrorCorrectionLevel() == null) {
	 * file.setErrorCorrectionLevel(ErrorCorrectionLevel.L); } if
	 * (StringUtils.isEmpty(file.getContent())) { return null; } if
	 * (StringUtils.isEmpty(file.getLogoPath())) { file.setLogoPath(""); } if
	 * (StringUtils.isEmpty(serverPath)) { serverPath =
	 * null;//Constant.IMGSERVER_HOST + "/fileManagerProject/upload.do"; }
	 * QRCode qr = new QRCode(); File file1 = qr.encode(file); return
	 * copyFileToServer("", file.getPath(), file.getPath() + "/" +
	 * file1.getName(), serverPath, null); }
	 */
}
